package com.org.manhu.chargehelper.ui;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

import com.org.manhu.chargehelper.ChargeApplication;
import com.org.manhu.chargehelper.R;
import com.org.manhu.chargehelper.broadcastreceiver.UpdateMoneyReceiver;
import com.org.manhu.chargehelper.broadcastreceiver.UpdateNickNameReceiver;
import com.org.manhu.chargehelper.constant.Constant;
import com.org.manhu.chargehelper.custom.BatteryCharger;
import com.org.manhu.chargehelper.custom.ExpandableTextView;
import com.org.manhu.chargehelper.custom.ImageBigPopwindow;
import com.org.manhu.chargehelper.custom.RoundCornersImageView;
import com.org.manhu.chargehelper.tools.AppManager;
import com.org.manhu.chargehelper.tools.JsonUtil;
import com.org.manhu.chargehelper.tools.LoadImage;
import com.org.manhu.chargehelper.tools.NetUtils;
import com.org.manhu.chargehelper.tools.SerializableMap;
import com.org.manhu.chargehelper.tools.Sever;
import com.org.manhu.chargehelper.tools.SharedPreferncesUtil;
import com.org.manhu.chargehelper.tools.StringUtils;
import com.org.manhu.chargehelper.tools.ToastUtils;
import com.org.manhu.chargehelper.webservice.AsyncProcessData;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

/**
 * @文件名：DetialActivity.java
 * @包名：com.org.manhu.chargehelper.ui
 * @作者：李朋辉 @QQ：892839211
 * @创建时间：2015年2月5日 上午9:48:25
 *
 * @描述：
 */
public class VideoDetialActivity extends Activity implements OnClickListener {

	private ImageView backIv, userInfoMoreIv;
	private Button cashOutBtn, exchangeBtn;

	private LinearLayout galleryArray;
	Integer[] images = { R.drawable.pic01, R.drawable.pic02, R.drawable.pic03,
			R.drawable.pic04, R.drawable.pic05 };
	DecimalFormat df = new DecimalFormat("0.00");

	private RoundCornersImageView appIconIv;
	private TextView appNameTv, awardTv, sizeTv, appSummaryTextTv;
	private Button downBtn;
	private TextView appSummaryTv;

	private TextView userNameTv, awardNumTv;

	private AsyncProcessData request;
	private Map<String, String> detialMap;
	private UpdateNickNameReceiver mReceiver;
	private UpdateMoneyReceiver receivers;
	private ImageBigPopwindow imagebigPopwindow;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (Constant.GET_APP_INFO.equals(msg.obj.toString())) {
				detialMap = JsonUtil.parseToMap(msg.getData().getString(
						"jsonStr"));
				if (detialMap != null) {
					setData(detialMap);
				}
			}
		}

	};

	private void setData(Map<String, String> map) {
		// TODO Auto-generated method stub

		LoadImage.LoadBigPic(map.get("IcoUrl"), appIconIv);
		appNameTv.setText(map.get("AppName"));
		awardTv.setVisibility(View.GONE);
		// awardTv.setText("兑换所需积分：" + map.get("UserPrice"));
		awardTv.setVisibility(View.GONE);
		String size = df.format(Float.parseFloat(map.get("Size"))
				/ (1024 * 1024))
				+ "M";
		sizeTv.setText(map.get("Tag") + " | " + size);
		appSummaryTv.setText(map.get("Digest"));

		List<String> list = JsonUtil.parseImageList(map.get("ImgList"));
		imagebigPopwindow = new ImageBigPopwindow(this, list);
		for (int i = 0; i < list.size(); i++) {
			galleryArray.addView(insertImage(list.get(i), i));
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_details);

		String appId = getIntent().getStringExtra("appid");
		request = new AsyncProcessData();
		requestData(appId);

		init();

		mReceiver = new UpdateNickNameReceiver(userNameTv);
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constant.ACTION_UPDATE_NICKNAME);
		registerReceiver(mReceiver, filter);

		receivers = new UpdateMoneyReceiver(awardNumTv);
		IntentFilter filters = new IntentFilter();
		filter.addAction(Constant.ACTION_UPDATE_MONEY);
		registerReceiver(receivers, filters);
	}

	/**
	 * @描述：
	 * @param appId
	 */
	private void requestData(String appId) {
		if (NetUtils.isConnected(this)) {
			request.getRequestData(mHandler, Constant.GET_APP_INFO, "appId",
					appId);
		} else {
			ToastUtils.showShort(this, "网络连接错误，请检查网络");
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		awardNumTv.setText(SharedPreferncesUtil.getMoney(this) + "");
		userNameTv.setText(SharedPreferncesUtil.getNickName(this));
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(mReceiver);
		unregisterReceiver(receivers);
	}

	/**
	 * @描述： 初始化控件，设置监听
	 */
	private void init() {
		AppManager.getAppManager().addActivity(this);

		backIv = (ImageView) findViewById(R.id.title_back);
		cashOutBtn = (Button) findViewById(R.id.tixian_btn);
		cashOutBtn.setVisibility(View.GONE);
		exchangeBtn = (Button) findViewById(R.id.exchange_btn);
		userInfoMoreIv = (ImageView) findViewById(R.id.user_info_more);
		galleryArray = (LinearLayout) findViewById(R.id.galleryArray);
		userNameTv = (TextView) findViewById(R.id.user_name);
		awardNumTv = (TextView) findViewById(R.id.user_award_num);
		appSummaryTextTv = (TextView) findViewById(R.id.detial_app_detial_text);
		appSummaryTextTv.setText("视频详情");
		awardNumTv.setText(SharedPreferncesUtil.getMoney(this) + "");
		userNameTv.setText(SharedPreferncesUtil.getNickName(this));

		appIconIv = (RoundCornersImageView) findViewById(R.id.detial_app_icon);
		appNameTv = (TextView) findViewById(R.id.activity_details_app_name);
		awardTv = (TextView) findViewById(R.id.activity_details_app_reward);
		sizeTv = (TextView) findViewById(R.id.activity_details_app_size);
		downBtn = (Button) findViewById(R.id.activity_detail_down_btn);
		appSummaryTv = (TextView) findViewById(R.id.activity_detial_app_summary);
		downBtn.setText("播放");

		userNameTv.setOnClickListener(this);
		backIv.setOnClickListener(this);
		userInfoMoreIv.setOnClickListener(this);
		downBtn.setOnClickListener(this);
		cashOutBtn.setOnClickListener(this);
		exchangeBtn.setOnClickListener(this);

		// appSummaryTv
		// .setText("《天天跑酷》十一矿仅有9M,无需联网即可运行的横版跑酷游戏。秉承《天天酷跑》、《旋风跑跑（WindRunner）》等游戏的优点，并在难度和操作体验上加以改善。画面清新，风格酷炫可爱，4款多变场景让你体验从沙漠穿越到北极的爽快。死亡还在点击复活？那就OUT了！快来体验宠物复生主人的无敌功能吧！让我们摆脱网络的束缚，变身九尾狐骑乘剑齿虎，在法老王的金字塔下尽情奔跑吧！");
		// for (int i = 0; i < images.length; i++) {
		// galleryArray.addView(insertImage(images[i], i));
		// }
	}

	// 原有方法加载本地资源
	private View insertImage(Integer id, int Rnum) {
		LinearLayout layout = new LinearLayout(getApplicationContext());
		layout.setLayoutParams(new LayoutParams(250, 370));
		layout.setGravity(Gravity.CENTER);
		ImageView imageView = new ImageView(getApplicationContext());
		imageView.setLayoutParams(new LayoutParams(240, 360));
		imageView.setOnClickListener(this);
		imageView.setId(Rnum);
		imageView.setBackgroundResource(id);

		layout.addView(imageView);
		return layout;
	}

	// 加载网络资源
	private View insertImage(String address, int Rnum) {
		LinearLayout layout = new LinearLayout(getApplicationContext());
		// int width = (int) (ChargeApplication.getScreenWidth() / 2);
		// int height = (int) (ChargeApplication.getScreenHeight() / 2.5);
		layout.setLayoutParams(new LayoutParams(250, 370));
		layout.setGravity(Gravity.CENTER);
		ImageView imageView = new ImageView(getApplicationContext());

		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(240, 360);
		lp.setMargins(16, 0, 0, 0);

		imageView.setId(Rnum);
		imageView.setOnClickListener(this);
		if (Rnum != 0) {
			imageView.setLayoutParams(lp);
		} else {
			imageView.setLayoutParams(new LayoutParams(240, 360));
		}
		String imagePath = StringUtils.formatPicture(address);
		Log.d("TAG", "图片路径：：" + imagePath);
		LoadImage.LoadBigPic(imagePath, imageView);
		// layout.addView(imageView);
		return imageView;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() >= 0 && v.getId() < 10) {
			imagebigPopwindow.showPopupWindow(backIv);
			imagebigPopwindow.currentimage(v.getId());
			return;
		}
		switch (v.getId()) {
		case R.id.title_back:
			this.finish();
			break;
		case R.id.tixian_btn:
			Intent it = new Intent(this, CashOutActivity.class);
			startActivity(it);
			break;
		case R.id.exchange_btn:
			Intent its = new Intent(this, ScanActivity.class);
			startActivity(its);
			break;
		case R.id.user_info_more:
			Intent intent = new Intent(this, CenterActivity.class);
			startActivity(intent);
			break;
		case R.id.user_name:
			Intent ite = new Intent(this, ModifyNickNameActivity.class);
			ite.putExtra("nickname", userNameTv.getText().toString());
			startActivity(ite);
			break;
		case R.id.activity_detail_down_btn:
			Intent intent1 = new Intent(Intent.ACTION_VIEW);
			Uri uri = Uri.parse(detialMap.get("DownUrl"));
			// 调用手机播放器播放视频
			intent1.setDataAndType(uri, "video/*");
			startActivity(intent1);
			break;
		}
	}

}
